﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpHelpers.IOs
{
    class FileMd5Signature
    {
        /// <summary>
        ///  获得文件MD5Key
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="laucherName">启动程序文件名</param>
        /// <returns></returns>
        private static string GetMd5SignatureKey(string filePath, string laucherName)
        {
            List<KeyValuePair<string, string>> fileList = FileHelper.GetFiles(filePath);

            var sb = new StringBuilder();

            foreach (var item in fileList.OrderBy(p => p.Value))
            {
                if (!item.Key.ToUpper().Contains("MD5"))
                {
                    if (!item.Key.ToUpper().Contains(laucherName))
                    {
                        var buffer = FileHelper.ReadFile(item.Value);
                        var temp = GetMd5HashFromFile(buffer);
                        sb.Append(temp);

                        buffer = null;

                    }
                }
            }

            var totalSingnatrueByte = Encoding.UTF8.GetBytes(sb.ToString()).ToList();
            totalSingnatrueByte.Add(0);

            string signature = GetMd5HashFromFile(totalSingnatrueByte.ToArray());
            return signature;
        }

        private static string GetMd5HashFromFile(byte[] buffer)
        {
            try
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(buffer);
                var sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(i.ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
    }
}
